package com.lagou.edu.core;

import com.lagou.edu.support.TransactionManager;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * TODO:
 *
 * @Author: wuyijie
 * @Date: 2021/11/17 21:28
 */
public class TransactionalBeanPostProcessor implements BeanPostProcessor{
    private DefaultListableBeanFactory beanFactory;

    public TransactionalBeanPostProcessor(DefaultListableBeanFactory beanFactory) {
        this.beanFactory= beanFactory;
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws Exception {
        TransactionManager transactionManager = (TransactionManager) beanFactory.getBean("TransactionManager");
        return Enhancer.create(bean.getClass(), new MethodInterceptor() {
            @Override
            public Object intercept(Object o1, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                Object invoke;
                try {
                    transactionManager.open();
                    //调用原来的方法
                    invoke = method.invoke(bean, objects);
                }catch (Exception e){
                    System.out.println("事务异常·····");
                    e.printStackTrace();
                    transactionManager.rollback();
                    throw e;
                } finally {
                    transactionManager.commit();
                }
                return invoke;
            }
        });
    }


}
